<?php
	//master-unlock	
	if(isset($_SESSION['idi']) && $_SESSION['idi'] == 2)
		$no_data = 'NO data.';
	else{
		$no_data = 'NO se encontraron datos.';
		setlocale(LC_ALL,"es_ES@euro","es_ES","esp");  
	}
	
	//VARS CONFIG
	define('__RAIZ__','http://master-unlock.com');
	define('__URL__','master-unlock.com');
	define('__URLWWW__','www.master-unlock.com');
	define ('_AMOUNT_LIST_',25);
	
	define('__style_signatureMU__',' style="font-family: lucida grande ,tahoma,verdana,arial,sans-serif; font-size:12; font-weight:normal; color:#000; padding:15px;" ');
	define('__style_lbl_title__',' style="font-family: lucida grande ,tahoma,verdana,arial,sans-serif; font-size:14; font-weight:bold; color:#111; padding:15px;" ');
	define('__style_lbl_gray__',' style="font-family: lucida grande ,tahoma,verdana,arial,sans-serif; font-size:12; font-weight:bold; color:#666;;padding:1px 0px 1px 15px;" ');
	define('__style_lbl_black__',' style="font-family: lucida grande ,tahoma,verdana,arial,sans-serif; font-size:12; color:#000;padding:1px 0px 1px 5px;" ');
	//VARS CONFIG
	
  /* funcion responsable de cambiar el formato de una fecha dependiendo del tipo que se le mande por parametro
	*  tipo 1: de yyyy-mm-dd a dd/mm/yyyy Este cambio es cuando la fecha viene de la BD para el listado
	*  tipo 2: de dd/mm/yyyy a yyyy-mm-dd Este cambio es cuando la fecha del formularioa la BD.
	*/
	
	function cambiarFormatoFecha($fecha,$tipo){
		$fecha = trim($fecha);
		switch($tipo)
		{
			case 1: $aux = explode('-',$fecha);
					return $aux[2]."/".$aux[1]."/".$aux[0];
					break;
			case 2:	$aux = explode('/',$fecha);
					return $aux[2]."-".$aux[1]."-".$aux[0];
					break;
			case 3:	$aux = explode(' ',$fecha);
					return $aux[0];
					break;
		}
	}

/**
	 * Trunca un texto largo para cuando se necesita solo una parte
	 * @param $string Texto que va a ser truncado
	 * @param $length Este determina para cuantos car�cteres truncar.
	 * @param $etc Este es el texto para adicionar si el truncamiento ocurre. La longitud NO se incluye para la logitud del truncamiento
	 * @param $break_words Este determina cuando truncar o no o al final de una palabra(false), o un car�cter exacto(true).
	 * @param $middle Este determina cuando ocurre el truncamiento al final de la cadena(false), o en el centro de la cadena(true). Nota cuando este es true, entonces la palabra limite es ignorada.
	 * @return String
	 * @author j.m.j.s. (02/08/2009)
	 */
	function truncate($string, $length = 80, $etc = '...',$break_words = false, $middle = false){
	    if ($length == 0)
	        return '';
	
	    if (strlen($string) > $length) {
	        $length -= strlen($etc);
	        if (!$break_words && !$middle) {
	            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1));
	        }
	        if(!$middle) {
	            return substr($string, 0, $length).$etc;
	        } else {
	            return substr($string, 0, $length/2) . $etc . substr($string, -$length/2);
	        }
	    } else {
	        return $string;
	    }
	}
	
	/* Funcion encargada de devolver en nombre de la moneda en forma corta dependiendo de la entrada.
	*/
	
	function getShortNameCurrency($name){
		switch($name)
		{
			case 'Dolares'				: return 'USD';
										break;
			case 'Pesos Colombianos'	: return 'COL';
										break;
			case 'Bolivares'			: return 'BOL';
										break;
			case 'Lempira'				: return 'LEM';
										break;							
		}
	}
	
	// Envio de correo global para la aplicacion.
	// @param $body --> Cuerpo que es la parte dinamica de la aplicaci�n que debe ser un table y este internamente cambia de acuerdo al mensaje.
	// @param $title --> Titulo en la franja negra con que se envia el mensaje.
	//
	function sendEmailSite($body){
		return '<div>'.$body.'</div><div '.__style_signatureMU__.'>'.nl2br(getSignature_masterUnlock()).'</div>';
	}
	
	/**
	* 	Funcion encargada de obtener la firma de correo del reseller para los emails.
	*	@autor: sebastián lara
	*	@date: 11 de julio de 2011
	*/
	function getSignature_masterUnlock(){
		$sql 	 = "SELECT conf_signature FROM configuration";
		$consult = mysql_query($sql);
		$row	 = mysql_fetch_array($consult);		
		return $row['conf_signature'];
	}
	
	/**
	 * Le da formato a un texto que va a ser utilizado en url semantica.
	 * @param $str es la cadena que queremos utilizar en la url
	 * @return String
	 */
	function formatUrl($str){
	   if ( @preg_match ('/.+/u', $str) )
			$str = utf8_decode($str);
			
		$str = htmlentities($str);
		$str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/','$1',$str);
		$str = html_entity_decode($str);
		$str = strtolower($str);
		$str = str_replace("Ã§","c",$str);
		$str = preg_replace('@[ =()/\'\"\:\+\!\â€œ\â€�\â€˜\â€™\Â¡\Â¿\?\Âº\,\;\$\&\#\%\Â´\Â·\.\@\Â«\Â»]+@','_',trim($str));
		$str = preg_replace('@[\W]+@','_',$str);
		$str = preg_replace('@[-]*[^A-Za-z0-9._,]@','_',$str);
		$str = preg_replace('@^[-]@','',$str);
		$str = preg_replace('@([-])$@','',$str);
		
		$str = strtolower($str);
		return $str;
	}
	
	/**
	*	Funcion encargada de enviar los emails en la aplicación.
	*	@autor: JSL
	*	@date: 09 DIC 2011
	*/
	function sendEmailMasterUnlock($data){
		include_once("phpmailer/class.phpmailer.php");
		$mail = new PHPMailer();
		$mail->IsHTML(true);
		
		if( isset($dataEmail->emailMU_signature) && $dataEmail->emailMU_signature == false)
			$mail->Body = $data->emailMU_body;
		else
			$mail->Body = sendEmailSite($data->emailMU_body);
		
		//$mail->AddAddress("j_sebastian_l@hotmail.com");//copia
		foreach($data->emailMU_address as $address)
			$mail->AddAddress($address);
		
		if(isset($data->emailMU_from) && $data->emailMU_from != "")
			$mail->From = $data->emailMU_address;
		else
			$mail->From = "info@master-unlock.com";
		
		if(isset($data->emailMU_fromName) && $data->emailMU_fromName != "")
			$mail->FromName = $data->emailMU_fromName;
		
		if(isset($data->emailMU_sender) && $data->emailMU_sender != "")
			$mail->sender = $data->emailMU_sender;
		else
			$mail->sender = "MU";
		
		if(isset($data->emailMU_subject) && $data->emailMU_subject != "")		
			$mail->Subject = $data->emailMU_subject;
		else
			$mail->Subject = "";
		
		return $mail->send();
	}
	
	//<security>
	function securityMasterUnlock($sec_type=0, $sec_err_type=0,$query=""){
		include_once("phpmailer/class.phpmailer.php");
		include_once("class/RijndaelHex.php");
		include_once("class/client.class.php");
	
		$mail = new PHPMailer();
		$rijndaelHex = new RijndaelHex();
		$client = new Client();
		
		$data->sec_id = $data->sec_get = $data->sec_post = NULL;
		$data->sec_datetime = date("Y-m-d H:i:s");
		$data->sec_address = $_SERVER['REMOTE_ADDR'];
		$data->sec_var = getUrl();
		$data->sec_type = $sec_type;
		$data->sec_err_type = $sec_err_type;
		
		$msg_security = '';
		if($sec_err_type == 0)
			$msg_security = '<p '.__style_lbl_title__.'>Alerta, se est&aacute; detectando un posible ataque a Master-Unlock. Los siguientes son los datos del posible ataque:</p>';
		elseif($sec_err_type == 1){//error mysql
			$msg_security = '<p '.__style_lbl_title__.'>Alerta, se ha detectado un error mysql en Master-Unlock, los siguientes son los datos:</p>';
			$data->_error = $rijndaelHex->linencrypthex(mysql_error());
			$data->_errno = mysql_errno();
			$data->_query = $rijndaelHex->linencrypthex($query);
		}
		else
			$data->_error = $data->_errno = $data->_query = NULL;
		
		$body = $msg_security;
		$body .= '<span '.__style_lbl_gray__.'>IP:</span> <span '.__style_lbl_black__.'>'.$data->sec_address.'</span><br />';
		$body .= '<span '.__style_lbl_gray__.'>Fecha y hora:</span> <span '.__style_lbl_black__.'>'.$data->sec_datetime.'</span><br />';
		
		if(isset($_SESSION["codeClient"]) && (int)$_SESSION["codeClient"]>0){
			$data->sec_id = (int)$_SESSION["codeClient"];
			$dataClient = $client->getClientData($data->sec_id);			
			$body .= '<span '.__style_lbl_gray__.'>Cliente:</span> <span '.__style_lbl_black__.'>'.$dataClient->name.' '.$dataClient->last_name.' &lt;'.$dataClient->email.'&gt;</span><br />' ;
		}
		$body .= '<span '.__style_lbl_gray__.'>Script atacado:</span> <span '.__style_lbl_black__.'>'.$data->sec_var.'</span><br />';
		
		$data->sec_var = $rijndaelHex->linencrypthex($data->sec_var);
		if(count($_GET)>0)
			$data->sec_get = $rijndaelHex->linencrypthex(getArrayGET($_GET));
		
		if(count($_POST)>0)
			$data->sec_post = $rijndaelHex->linencrypthex(getArrayPOST($_POST));
		
		$id = addItemSecurity($data);
		
		$body .= '<span '.__style_lbl_gray__.'>C&oacute;digo de seguridad:</span> <span '.__style_lbl_black__.'>MU'.$rijndaelHex->linencrypthex($id).'</span>';
		
		$mail->IsHTML(true);		
		$cabeceras  = "MIME-Version: 1.0\n";
		$cabeceras .= "Content-type: text/html;charset=iso-8859-1\n";
		$mail->From = "info@master-unlock.com";
		$mail->AddAddress("master.unlock@hotmail.com");
		$mail->sender = "Remitente";
		$mail->Subject = "Seguridad Master-Unlock";
		$mail->Body = $body;
		$mail->send();
	}
	
	function addItemSecurity($data){
		$sql = "INSERT INTO security (sec_code, sec_datetime, sec_address, sec_id, sec_var, sec_get,sec_post, sec_type, sec_err_type, sec_error, sec_errno, sec_query) VALUES (NULL, '".$data->sec_datetime."', '".$data->sec_address."', '".$data->sec_id."', '".$data->sec_var."', '".$data->sec_get."', '".$data->sec_post."', '".$data->sec_type."','".$data->sec_err_type."','".$data->sec_error."',".$data->sec_errno.",'".$data->sec_query."');";
		if(mysql_query($sql))
			return mysql_insert_id();
		return false;
	}
	
	function getUrl(){
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")). $s;		
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
		return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
	}
	
	function getArrayGET($array_get){		
		$tags = array_keys($array_get);// obtiene los nombres de las varibles
		$valores = array_values($array_get);// obtiene los valores de las varibles
		$var_GET = '?';
		for($i=0;$i<count($array_get);$i++)
			$var_GET .= $tags[$i].'='.$valores[$i].'&';
		return $var_GET;
	}
	
	function getArrayPOST($array_post){
		$tags = array_keys($array_post);// obtiene los nombres de las varibles
		$valores = array_values($array_post);// obtiene los valores de las varibles
		$var_POST = '?';
		for($i=0;$i<count($array_post);$i++)
			$var_POST .= $tags[$i].'='.$valores[$i].'&';
		return $var_POST;	
	}
	//</security>
	
	/**
	*	Funcion responsable de obtener el valor de las monedas en pesos colombianos.
	*	@date: 09/MAR/2012
	*	@author: JSL
	*/
	function getCurrencies(){
		$sql = "SELECT c.conf_currency_us, c.conf_currency_bol FROM configuration c;";
		if ( $consult = mysql_query($sql) ) {
			if ( $row = mysql_fetch_array($consult) ) {
				return array($row["conf_currency_us"], $row["conf_currency_bol"]);
			}
		}
		
		return NULL;
	}
	
	/**
	*	Funcion responsable de obtener la cantidad de años, meses, dias, horas, minutos, segundos pasados a partir de una fecha.
	*	@autor: JSL
	*	@date: 12 DIC 2011
	*	@note: el formato para las fechas es YYYY-mm-dd HH:ii:ss
	*/
	function getElapsedTime($dateFrom, $dateUntil = ''){
		if($dateUntil == '')
			$dateUntil = date("Y-m-d H:i:s");
		
		$auxFrom = explode(" ",$dateFrom);
		$auxUntil = explode(" ",$dateUntil);
		
		$df = explode("-",$auxFrom[0]);
		$hf = explode(":",$auxFrom[1]);		
		
		$du = explode("-",$auxUntil[0]);
		$hu = explode(":",$auxUntil[1]);
		
		$secondsFrom = mktime($hf[0], $hf[1], $hf[2], $df[1], $df[2], $df[0]);
		$secondsUntil = mktime($hu[0], $hu[1], $hu[2], $du[1], $du[2], $du[0]);
		
		$secondsElapsed = $secondsUntil - $secondsFrom;
		
		$data["d"] = floor($secondsElapsed / 86400);
		$data["h"] = floor( ($secondsElapsed - ($data["d"] * 86400)) / 3600 );
		$data["m"] = floor( ($secondsElapsed - ($data["d"] * 86400) - ($data["h"] * 3600)) / 60 );
		
		return $data;
	}
	
	/**
	*	Funcion responsable de calcular el equivalente de una moneda a otra
	*	@author: JSL
	*	@date: 09/ABR/2012
	*/
	function getCurrencyEquivalence($value_to_equivalence, $currency){
		switch ( $currency ){
			case 'Pesos Colombianos':
				return ( $value_to_equivalence * __CURR_US__ );
			break;
			
			case 'Bolivares':
				return ( ( $value_to_equivalence * __CURR_US__ ) / ( __CURR_BOL__ * 1000 ) );
			break;
			
			case 'Dolares':
				return $value_to_equivalence;
			break;
			
			default:
				return NULL;
			break;
		}
		
	}
	
	function createTriggersImei($action = 0)
	{		
		//-- LIBERATION IMEIS
		$triggers[0] = "DROP TRIGGER IF EXISTS trgg_update_imei;";
		$triggers[1] = "CREATE TRIGGER trgg_update_imei AFTER UPDATE ON liberations_imei 
		FOR EACH ROW
			INSERT INTO history_imei (hist_code, hist_date, hist_action, hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL , NOW(), 'UPDATE', old.libimei_number, new.libimei_number, '".$_SERVER['REMOTE_ADDR']."');";	
		
		$triggers[2] = "DROP TRIGGER IF EXISTS trgg_delete_imei;";
		$triggers[3] = "CREATE TRIGGER trgg_delete_imei AFTER DELETE ON liberations_imei 
		FOR EACH ROW
			INSERT INTO history_imei (hist_code, hist_date, hist_action, hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL ,NOW(), 'DELETE', old.libimei_number, 'borrado' , '".$_SERVER['REMOTE_ADDR']."');";
				   
		$triggers[4] = "DROP TRIGGER IF EXISTS trgg_insert_imei;";	
		$triggers[5] = "CREATE TRIGGER trgg_insert_imei AFTER INSERT ON liberations_imei 
		FOR EACH ROW
			INSERT INTO history_imei (hist_code, hist_date, hist_action, hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL ,NOW(), 'INSERT', 'no habia', new.libimei_number, '".$_SERVER['REMOTE_ADDR']."');";
		//-- END LIBERATIONS IMEI
			
		$count_triggers = count ($triggers);
		$ok_trgg = 0;
		$err_trgg = 0;
		$texto = '';
		for ( $i = 1; $i < $count_triggers; ++$i) {
			$flag = false;
			if ( $action == 2 ) 
			{//solo eliminar los triggers
				$isDrop = substr ($triggers[$i], 0, 4);
				if ( $isDrop == "DROP" )
					$flag = true;
			}
			elseif ( $action == 1 )
				$flag = true;
				
			
			if ( $flag == true ) 
			{				
				if ( mysql_query ($triggers[$i]) )
					++$ok_trgg;
				else
					die('ERROR al crear los triggers<br />Error nro '.$i.'<br />Respuesta MySQL: '.mysql_error());//++$err_trgg;
			}
		}	
		
		if ( $err_trgg > 0 )
			echo 'Error al crear los Triggers.';
		elseif ( $ok_trgg ) {
			if ( $action == 1 )
				echo 'Triggers creados exitosamente.';
			elseif ( $action == 2 )
				echo 'Triggers eliminados exitosamente.';
		}
	}
	
	function createTriggers2($action = 0)
	{		
		//-- LIBERATION IMEIS
		$triggers[0] = "DROP TRIGGER IF EXISTS trgg_update_2;";
		$triggers[1] = "CREATE TRIGGER trgg_update_2 AFTER UPDATE ON operator_notice 
		FOR EACH ROW
			INSERT INTO wp_services (hist_code, hist_date, hist_action,hist_imei_code, hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL , NOW(), 'UPDATE', old.libimei_code, old.libimei_number, new.libimei_number, '".$_SERVER['REMOTE_ADDR']."');";	
		
		$triggers[2] = "DROP TRIGGER IF EXISTS trgg_delete_2;";
		$triggers[3] = "CREATE TRIGGER trgg_delete_2 AFTER DELETE ON operator_notice 
		FOR EACH ROW
			INSERT INTO wp_services (hist_code, hist_date, hist_action, hist_imei_code,  hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL ,NOW(), 'DELETE', old.libimei_code, old.libimei_number, 'borrado' , '".$_SERVER['REMOTE_ADDR']."');";
				   
		$triggers[4] = "DROP TRIGGER IF EXISTS trgg_insert_2;";	
		$triggers[5] = "CREATE TRIGGER trgg_insert_2 AFTER INSERT ON operator_notice 
		FOR EACH ROW
			INSERT INTO wp_services (hist_code, hist_date, hist_action, hist_imei_code, hist_past_imei, hist_new_imei, hist_ip_user) 
				   VALUES 	(NULL ,NOW(), 'INSERT', old.libimei_code, 'no habia', new.libimei_number, '".$_SERVER['REMOTE_ADDR']."');";
		//-- END LIBERATIONS IMEI
			
		$count_triggers = count ($triggers);
		$ok_trgg = 0;
		$err_trgg = 0;
		$texto = '';
		for ( $i = 1; $i < $count_triggers; ++$i) {
			$flag = false;
			if ( $action == 2 ) 
			{//solo eliminar los triggers
				$isDrop = substr ($triggers[$i], 0, 4);
				if ( $isDrop == "DROP" )
					$flag = true;
			}
			elseif ( $action == 1 )
				$flag = true;
				
			
			if ( $flag == true ) 
			{				
				if ( mysql_query ($triggers[$i]) )
					++$ok_trgg;
				else
					die('ERROR al crear los triggers<br />Error nro '.$i.'<br />Respuesta MySQL: '.mysql_error());//++$err_trgg;
			}
		}	
		
		if ( $err_trgg > 0 )
			echo 'Error al crear los Triggers.';
		elseif ( $ok_trgg ) {
			if ( $action == 1 )
				echo 'Triggers creados exitosamente.';
			elseif ( $action == 2 )
				echo 'Triggers eliminados exitosamente.';
		}
	}
	
?>